package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.constants.admin.AdminConstants;
import com.heima.common.exception.CustomException;
import com.heima.feigns.article.ArticleFeign;
import com.heima.feigns.wemedia.WemediaFeign;
import com.heima.model.article.pojos.ApAuthor;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.AuthDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.user.pojos.ApUserRealname;
import com.heima.model.wemedia.pojos.WmUser;

import com.heima.user.mapper.ApUserRealnameMapper;
import com.heima.user.service.ApUserRealnameService;
import com.heima.user.service.ApUserService;

import io.seata.spring.annotation.GlobalTransactional;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


import javax.annotation.Resource;
import java.util.Date;



@Service
public class ApUserRealnameServiceImpl extends ServiceImpl<ApUserRealnameMapper,ApUserRealname> implements ApUserRealnameService {

    @Autowired
    ApUserService apUserService;

    @Override
    public ResponseResult loadListByStatus(AuthDto dto) {
        //检查参数
     if (dto==null){
         return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
     }
     dto.checkParam();
        //设置分页条件，设置查询条件
        Page<ApUserRealname> page = new Page<>(dto.getPage(), dto.getSize());
        LambdaQueryWrapper<ApUserRealname> wrapper = new LambdaQueryWrapper();
        if (dto.getStatus()!=null){
            wrapper.eq(ApUserRealname::getStatus, dto.getStatus());
        }
        IPage<ApUserRealname> pageResult = page(page, wrapper);
        PageResponseResult pageResponseResult = new PageResponseResult(dto.getPage(), dto.getSize(), (int) pageResult.getTotal());
        pageResponseResult.setData(pageResult.getRecords());

        //返回查询结果
        return pageResponseResult;
    }
    @GlobalTransactional
    @Override
    public ResponseResult updateStatusById(AuthDto dto, Short status) {

        //1. 检查参数
        if (dto == null || dto.getId() == null) {
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID);
        }
        // 2. 根据ID查询实名认证信息
        ApUserRealname userRealname = getById(dto.getId());
        if (userRealname == null) {
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID);
        }
        // 3. 判断实名认证状态是否为待审核
        if (userRealname.getStatus() != AdminConstants.WAIT_AUTH) {
            throw new CustomException(AppHttpCodeEnum.AP_USER_DATA_NOT_INVALID);
        }
        // 4. 查询实名认证用户关联的ap_user信息
        //ApUser apUser = ApUserService.selectById(userRealname.getUserId());
        ApUser apUser = apUserService.getById(userRealname.getUserId());
        if (apUser == null) {
            throw new CustomException(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        // 5. 更新实名认证信息
        userRealname.setStatus(status);
        userRealname.setUpdatedTime(new Date());
        if (StringUtils.isNotBlank(dto.getMsg())) {
            userRealname.setReason(dto.getMsg());
        }
//        if (!IdCardUtils.checkIdCardInfo(userRealname.getName(),userRealname.getIdno())){
//            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID,"用户身份证信息错误");
//        }
        updateById(userRealname);
        // 6. 如果 审核结果为 通过(9) 生成自媒体账号，生成作者信息
        if (status.intValue() == AdminConstants.AD_USER_ISSTATUS) {
            WmUser wmUser = createWmUser(apUser);
            if (wmUser == null) {
                throw new CustomException(AppHttpCodeEnum.SERVER_ERROR,"创建自媒体用户失败");
            }
            createAuthor(wmUser);
        }
        //int i=(1/0);
        // 7. 当前用户为自媒体人
        apUser.setFlag((short) 1);
        apUser.setIdentityAuthentication(true);// 身份认证通过
        boolean b = apUserService.save(apUser);
        return ResponseResult.okResult();
    }
        /**
         * 创建作者信息
         * @param wmUser
         */

        @Autowired
        ArticleFeign articleFeign;
        private void createAuthor(WmUser wmUser) {
            ApAuthor author = articleFeign.findByUserId(wmUser.getApUserId());
            if (author!=null){
                throw new CustomException(AppHttpCodeEnum.DATA_EXIST,"用户已经存在");
            }
            author = new ApAuthor();
            author.setName(wmUser.getName());
            author.setType(2);
            author.setUserId(wmUser.getApUserId());
            author.setCreatedTime(new Date());
            author.setWmUserId(wmUser.getId());
            ResponseResult result = articleFeign.save(author);
            if (result.getCode()!=0){
                throw new CustomException(AppHttpCodeEnum.DATA_NOT_EXIST);
            }
        }

        /**
         * 创建自媒体用户
         * @param dto
         * @param apUser
         * @return
         */

        @Autowired
        WemediaFeign wemediaFeign;

        public WmUser createWmUser(ApUser apUser) {
            String name = apUser.getName();
            WmUser wmUser = wemediaFeign.findByName(name);
            if (wmUser != null) {
                throw new CustomException(AppHttpCodeEnum.DATA_EXIST, "自媒体用户已经存在");
            }
            wmUser = new WmUser();
            wmUser.setApUserId(apUser.getId());
            wmUser.setName(apUser.getName());
            wmUser.setPassword(apUser.getPassword());
            wmUser.setSalt(apUser.getSalt());
            wmUser.setImage(apUser.getImage());
            wmUser.setPhone(apUser.getPhone());
            wmUser.setStatus(AdminConstants.AD_USER_ISSTATUS);
            wmUser.setType(0);
            wmUser.setCreatedTime(new Date());
            return wemediaFeign.save(wmUser);
        }
}
